%this function helps to remove the the background noise from the light.
%It mainly use the function fringeremoval to do the task
%It has 3 mode, read the mode discussion carefully when used
%It need <refimagesIniDirectory> to store the reference images
%database,currently set as 'D:\Rb87Files\refimagesIni.mat'
%Version beta 1.0 2015/6/15


%User Panel---------------------------------------------------------------

mode=0; %0 create the initial refdatabase, 1 roll in ref and calculate, 2 real time ref and calculate for specified photoNamePre 3 real time ref and calculate
overWrite=1;
%leftup[x,y,w,h]
% ROI=[120,30,230,482];
% ROI=[84,129,600,500];
ROI=[50,50,800,800];
atomSumRange=[196,241,80,80];

sigma_cross=1.356; %10-9
pixelWidth=3.9; %um

photoStart=557;
photoEnd=806;
% photoEnd=347;

refNum=250;

checkCycle=0.01;%second

clims=[-0.05,0.8];
%files specification-------------------------------------------------------

% folderName='E:\20150603morning\4552\';
% photoNamePre='455206031009_';

% folderName='E:\20150604morning\4552\';
% photoNamePre='45521506041737_';

folderName='\\BEC-DELL\ShareFolder\20170525morning\ikon-17639\';
photoNamePre='17639test_';
% folderName='E:\shareFolder\20150720afternoon\4552\';
% photoNamePre='45521507201049_';
refimagesIniDirectory='F:\Rb87Files\refimagesIni.mat';

% folderName='E:\shareFolder\20150704morning\4550\';
% photoNamePre='45501507041002_';
% refimagesIniDirectory='D:\Rb87Files\refimagesIni4550.mat';

%------------------------------------------------------------------------

% addpath(genpath('ExperimentBasicFunction'));

targetPhotoList=photoStart:photoEnd;
% targetPhotoList=[800,819,889,892,894,900,906,841]
    
% if photoStart>refNum
%     refInd=(photoStart-refNum+1):photoStart;
% else
    refInd=photoStart:(photoStart+refNum-1);
% end


if mode==0
    if exist(refimagesIniDirectory,'file')==2
        refimagesIniStruct=load(refimagesIniDirectory);
        refimagesIni=refimagesIniStruct.refimagesIni;
        
        if size(refimagesIni,3)==refNum
            refimages=refimagesIni;
        else
            error('Error: refNum ~= loaded reference images');
        end
    end
    
     
    refInd=photoStart:min((photoStart+refNum-1),photoEnd);
    refimagesIni(:,:,mod(refInd,refNum)+1)=refCreate(refInd,'bg',folderName,photoNamePre,1024);
    save(refimagesIniDirectory','refimagesIni');
else 
    refimagesIniStruct=load(refimagesIniDirectory);
    refimagesIni=refimagesIniStruct.refimagesIni;
    
    if size(refimagesIni,3)==refNum
        refimages=refimagesIni;
    else
        error('Error: refNum ~= loaded reference images');
    end
    
    bgmask=ones(1024,1024);
    ROIX_vector=ROI(1):(ROI(1)+ROI(3));
    ROIY_vector=ROI(2):(ROI(2)+ROI(4));
    bgmask(ROIY_vector,ROIX_vector)=0;

    if mode==1

        for photoInd=targetPhotoList
            %data input
%             if photoInd>refInd(end) %roll in another ref image  there might be problem with the mod
                refimages(:,:,mod(photoInd-photoStart-1,refNum)+1)=refCreate(photoInd,'bg',folderName,photoNamePre,1024);
%             end
            
            absimages=loadPhoto(photoName(folderName,photoNamePre,photoInd,'.asc'));
            nolimage=loadPhoto(photoName(folderName,photoNamePre,photoInd,'nolight.asc'));
%             absimages=refCreate(photoInd,'',folderName,photoNamePre);
%             nolimage=refCreate(photoInd,'nolight',folderName,photoNamePre);
            
            %calculate
            refimageCal=fringeremoval(absimages,refimages,bgmask);
            refimageCalMNolight=((refimageCal-nolimage)+abs(refimageCal-nolimage))/2+1;
            absimageMNolight=((absimages-nolimage)+abs(absimages-nolimage))/2+1;

            figure(11);
            odimage=log(  refimageCalMNolight./absimageMNolight  );
            imagesc(odimage,[-0.2,0.1]);
            title(num2str(photoInd));
            rectangle('position',ROI);
            print( '-dpng','-r500', [folderName num2str(photoInd)]);
%             im=reshape(odimage(1:200,1:1024),200*1024,1);
%             difference=var(im)
        
            %save as mat files
            if photoInd<10
                savefilename=strcat(folderName,photoNamePre,'00',num2str(photoInd),'od.mat');%ͨ��ͳһ��������ʽ����ѭ�����㡣J:\SOCTc\F2013-02-23\RamanRabi
            else if (photoInd>=10)&&(photoInd<100)
                savefilename=strcat(folderName,photoNamePre,'0',num2str(photoInd),'od.mat');
            else photoInd>=100;
                savefilename=strcat(folderName,photoNamePre,num2str(photoInd),'od.mat');
                end 
            end
            save(savefilename,'odimage');
        end
        save(refimagesIniDirectory,'refimagesIni');
    elseif mode==2 
            cd(folderName);
            newestDatenum=0;
            photoInd=photoStart;
            
            while(true)
                if exist(photoName(folderName,photoNamePre,photoInd,'nolight.asc'),'file')  
                    if overWrite==0 && exist(photoName(folderName,photoNamePre,photoInd,'od.mat'),'file')==2
                        disp([photoName(folderName,photoNamePre,photoInd,'od.mat') ' already exist, skip it']);
                        photoInd=photoInd+1;
                        continue;
                    end
                    absimages=loadPhoto(photoName(folderName,photoNamePre,photoInd,'.asc'));
                    refimages(:,:,mod(photoInd,refNum)+1)=loadPhoto(photoName(folderName,photoNamePre,photoInd,'bg.asc'));
                    nolimage=loadPhoto(photoName(folderName,photoNamePre,photoInd,'nolight.asc'));
                    
                    %calculate
                    refimageCal=fringeremoval(absimages,refimages,bgmask);
                    refimageCalMNolight=((refimageCal-nolimage)+abs(refimageCal-nolimage))/2+1;
                    absimageMNolight=((absimages-nolimage)+abs(absimages-nolimage))/2+1;                
                    odimage=log(  refimageCalMNolight./absimageMNolight  );
                    
                    figure(1);
                    imagesc(odimage,clims);
                    title(photoName(folderName,photoNamePre,photoInd,''));
                    rectangle('position',ROI);
                    
                    
%                     rectangle('position',atomSumRange);
                    atomX=atomSumRange(1):(atomSumRange(1)+atomSumRange(3));
                    atomY=atomSumRange(2):(atomSumRange(2)+atomSumRange(4));
                    atomCut=odimage(atomY,atomX);
                    atomSum=pixelWidth*pixelWidth*10/sigma_cross*sum(sum(atomCut));
                    text(400,100,['N=' num2str(atomSum,'%10.3e')], 'BackgroundColor','w');
                    
                    savefilename= photoName(folderName,photoNamePre,photoInd,'od.mat');
                    save(savefilename,'odimage');

                    %incase the program is interrupted
                    save(refimagesIniDirectory,'refimagesIni');
%                     fprintf( '%s\n\n', [newPhotoNamePre ' calculate finished, refimages saved'] );
                
                    photoInd=photoInd+1;
                else
                    
                    pause(checkCycle);
                end
                
            end
    elseif mode==3
            cd(folderName);
            newestDatenum=0;
            count=1;
            
            while(true)
                ascfiles=dir('*nolight.asc');
                [datenum,index] = sort(cell2mat({ascfiles.datenum}),'descend');
                
                if newestDatenum==0
                    newestDatenum=datenum(1);
                end
                if newestDatenum>=datenum(1) 
                     pause(checkCycle);
                    continue;
                end
                
                % if found new photo, get the names
                name={ascfiles.name};
                name=name(index);
                newRefName=name{1};
                newPhotoNamePre=newRefName(1:(strfind(newRefName,'nolight.asc')-1));
                
                %data input
                pause(0.2);
                absimages=loadPhoto([folderName newPhotoNamePre '.asc']);
                refimages(:,:,mod(count,refNum)+1)=loadPhoto([folderName newPhotoNamePre 'bg.asc']);
                nolimage=loadPhoto([folderName newPhotoNamePre 'nolight.asc']);
                ascfiles=dir('*bg.asc');%renew the reading modification
                [datenum,index] = sort(cell2mat({ascfiles.datenum}),'descend');
                newestDatenum=datenum(1);

                %calculate
                refimageCal=fringeremoval(absimages,refimages,bgmask);
                refimageCalMNolight=((refimageCal-nolimage)+abs(refimageCal-nolimage))/2+1;
                absimageMNolight=((absimages-nolimage)+abs(absimages-nolimage))/2+1;

                figure(1);
                odimage=log(  refimageCalMNolight./absimageMNolight  );
                imagesc(odimage);
                title([folderName newPhotoNamePre]);
                rectangle('position',ROI);

                %save as mat files
%                 if photoInd<10
%                     savefilename=strcat(folderName,photoNamePre,'00',num2str(photoInd),'od.mat');%ͨ��ͳһ��������ʽ����ѭ�����㡣J:\SOCTc\F2013-02-23\RamanRabi
%                 else if (photoInd>=10)&&(photoInd<100)
%                     savefilename=strcat(folderName,photoNamePre,'0',num2str(photoInd),'od.mat');
%                 else photoInd>=100;
%                     savefilename=strcat(folderName,photoNamePre,num2str(photoInd),'od.mat');
%                     end 
%                 end
                savefilename=[folderName newPhotoNamePre 'od.mat'];
                save(savefilename,'odimage');
                
                %incase the program is interrupted
                save(refimagesIniDirectory,'refimagesIni');
%                 fprintf( '%s\n\n', [newPhotoNamePre ' calculate finished, refimages saved'] );
            end
    end
end